package com.pray.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pray.entity.po.PrayMessage;
import com.pray.mapper.PrayMessageMapper;
import com.pray.service.PrayMessageService;
import com.pray.utils.PrayConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author Rainy-Heights
* @description 针对表【pray_message(公告通知)】的数据库操作Service实现
* @createDate 2023-09-10 00:29:21
*/
@Service
public class PrayMessageServiceImpl extends ServiceImpl<PrayMessageMapper, PrayMessage>
    implements PrayMessageService{
    private static final DateTimeFormatter timeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;
    @Override
    public List<PrayMessage> selectLatestPublish(String time) {
        //获取当前时间参数，将对应的最近公告查询并返回，同时存入Redis中作为热点数据
        LocalDateTime now = LocalDateTime.now();
        //转换时间，前端传输时间格式：yyyy-MM-dd HH:mm:ss
        Duration between = Duration.between(now, LocalDateTime.parse(time,timeFormatter));
        long seconds = between.getSeconds();
        //判断传入时间和最近发布的消息是否相隔三天时间
        if (seconds >= PrayConstants.RECENT_DAYS){
            //没查到数据缓存空对象，防止缓存穿透
            PrayMessage message = new PrayMessage();
            message.setContents("最近三日内没有发布最新的公告");
            LinkedList<PrayMessage> prayMessages = new LinkedList<>();
            prayMessages.add(message);
            return  prayMessages;
        }
        List<PrayMessage> prayMessages = (List<PrayMessage>) redisTemplate.opsForValue().get(PrayConstants.PRAY_NOTICE);
        if (prayMessages ==null){
            List<PrayMessage> messageList = query().gt("publish_time", seconds).list();
            redisTemplate.opsForValue().set(PrayConstants.PRAY_NOTICE,messageList,PrayConstants.RECENT_DAYS, TimeUnit.SECONDS);
            return messageList;
        }
        return prayMessages;
    }
}




